#!/usr/bin/python
'''
Runs multiple threads of sam_to_ham in parallel.
'''
import subprocess
import sys
import os
import time

# parameters.
sam_dir = sys.argv[1]
ham_dir = sys.argv[2]
log_dir = sys.argv[3]
num_threads = int(sys.argv[4])
num_jobs = int(sys.argv[5])

wait = 60

# waits for a slot to open up.
def waitforit(procs, clean=False):
	while len(procs) > 0:
		# check ever process for progress.		
		for i in range(len(procs)):
			pr = procs[i][0].poll()
			if pr == None: continue
			else:
				# close log.
				procs[i][1].close()
				del procs[i]
				
				# what to do when ends.
				if clean == True: break
				else: return procs
		# sleep.
		time.sleep(wait)
	return procs


# get sam files.
sam_files = os.listdir(sam_dir)

# loop over jobs.
jobs = []
for sam_file in sam_files:
	# make command.
	sf = "%s/%s" % (sam_dir, sam_file)
	hf = "%s/%s" % (ham_dir, sam_file.replace(".sam",".ham"))
	lf = "%s/%s" % (log_dir, sam_file.replace(".sam",".log"))
	cmd = ["sam_to_ham_parallel.py", sf, hf, str(num_threads)]

	
	# wait for opportunity to execute.
	if len(jobs) > num_jobs:
		jobs = waitforit(jobs)
		
	# execute job.
	fout = open(lf, "w")
	proc = subprocess.Popen(cmd, stdout=fout, stderr=fout)
	jobs.append((proc, fout))
